
#include"share_memory.h"


int shmid, i;
int* addr;


void share_memory()
{
	while ((i = fork()) == -1)
	{
		;
	}
	if (!i)
	{
		share_server();
	}
	system("ipcs -m");
	while ((i = fork()) == -1)
	{
		;
	}
	if (!i)
	{
		share_client();
	}
	wait(0);
	wait(0);
}

void share_client()
{
	int i;
	shmid = shmget(SHMKEY, 1024, 0777);
	addr = shmat(shmid, 0, 0);
	for(i = 9; i >= 0; i-- )
	{
		while(*addr != -1)
		{
			;
		}
		printf("client sent\n");
		*addr = i;
	}
	exit(0);
}

void share_server()
{
	shmid = shmget(SHMKEY, 1024, 0777 | IPC_CREAT);
	addr = shmat(shmid, 0, 0);
	do
	{
		*addr = -1;
		while(*addr == -1)
		{
			;
		}
		printf("server received\n");
	} while(*addr);
	shmctl(shmid, IPC_RMID, 0);
	exit(0);
}


